<template>
  <el-tooltip v-if="tooltip" :effect="tooltipEffect" :content="tooltip" :placement="placement">
    <el-button
      circle
      :size="size"
      :icon="icon"
      :class="[{ 'is-active': value === label }, { 'is-disabled': isDisabled }, { 'is-focus': focus }]"
      @click="handleChange"
      :disabled="isDisabled"
      @keydown.space.stop.prevent="handleChange"
    >
      <slot></slot>
      <template v-if="!icon">{{ label }}</template>
    </el-button>
  </el-tooltip>

  <el-button
    v-else
    circle
    :size="size"
    :icon="icon"
    :class="[{ 'is-active': value === label }, { 'is-disabled': isDisabled }, { 'is-focus': focus }]"
    @click="handleChange"
    :disabled="isDisabled"
    @keydown.space.stop.prevent="handleChange"
  >
    <slot></slot>
    <template v-if="!icon">{{ label }}</template>
  </el-button>
</template>
<script>
import Emitter from 'element-ui/lib/mixins/emitter'

export default {
  name: 'MToolboxItem',

  mixins: [Emitter],

  inject: {
    elForm: {
      default: '',
    },
    elFormItem: {
      default: '',
    },
  },

  props: {
    label: {},
    disabled: {
      type: Boolean,
      default: false,
    },

    icon: String,

    placement: {
      type: String,
      default: 'bottom',
    },
    tooltip: String,
    tooltipEffect: {
      type: String,
      default: 'light',
    },
  },
  data() {
    return {
      focus: false,
    }
  },
  computed: {
    value: {
      get() {
        return this._radioGroup.value
      },
      set(value) {
        this._radioGroup.$emit('input', value)
      },
    },
    _radioGroup() {
      let parent = this.$parent
      while (parent) {
        if (parent.$options.componentName !== 'ElRadioGroup') {
          parent = parent.$parent
        } else {
          return parent
        }
      }
      return false
    },
    activeStyle() {
      return {
        backgroundColor: this._radioGroup.fill || '',
        borderColor: this._radioGroup.fill || '',
        boxShadow: this._radioGroup.fill ? `-1px 0 0 0 ${this._radioGroup.fill}` : '',
        color: this._radioGroup.textColor || '',
      }
    },
    _elFormItemSize() {
      return (this.elFormItem || {}).elFormItemSize
    },
    size() {
      return this._radioGroup.radioGroupSize || this._elFormItemSize || (this.$ELEMENT || {}).size
    },
    isDisabled() {
      return this.disabled || this._radioGroup.disabled || (this.elForm || {}).disabled
    },
    tabIndex() {
      return this.isDisabled || (this._radioGroup && this.value !== this.label) ? -1 : 0
    },
  },

  methods: {
    handleChange() {
      this.value = this.isDisabled ? this.value : this.label
      this.$nextTick(() => {
        this.dispatch('ElRadioGroup', 'handleChange', this.value)
      })
    },
  },
}
</script>

<style lang="scss" scoped>
.el-radio-group {
  .el-button + .el-button {
    margin-left: 5px;
  }
}
</style>
